package utils

import (
	"io"
	"math/rand"
	"os"
	"regexp"
	"time"
	"unicode/utf8"
)

func SaveFile(url string, filename string) error {
	resp, err := Get(url).Response()
	if err != nil {
		return err
	}
	out, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer out.Close()
	defer resp.Body.Close()
	io.Copy(out, resp.Body)
	ChangeMd5(out)
	return nil
}

func DeleteFile(filename string) error {
	return os.Remove(filename)
}

func ChangeMd5(reader io.WriteSeeker) {
	rand.Seed(time.Now().UnixNano())
	num := 2 + rand.Intn(8)
	reader.Seek(0, os.SEEK_END)
	newbuf := make([]byte, num)
	reader.Write(newbuf)
}

func ChangeMd5_Bytes(body []byte) []byte {
	rand.Seed(time.Now().UnixNano())
	num := 2 + rand.Intn(8)
	newbuf := make([]byte, num)
	return append(body, newbuf...)
}

// v2表示是否2个符号为1个字符
func TitleCount(str string, v2 bool) int {
	if !v2 {
		return utf8.RuneCountInString(str)
	}

	xx := regexp.MustCompile(`[a-z0-9A-Z\p{P}]`)
	cnt, abc := 0, 0
	for _, s := range str {
		if xx.MatchString(string(s)) {
			abc++
		} else {
			cnt++
		}
	}
	cnt += abc / 2
	if abc%2 > 0 {
		cnt++
	}
	return cnt
}
